<?php

namespace app\admin\services;

use app\admin\model\AdminModel;
use app\admin\model\ShopModel;
use think\facade\Route as Url;
use think\facade\Validate;

/**
 * Class BaseServices
 * @package app\services
 */
abstract class BaseService
{
    /**
     * 模型注入
     * @var object
     */
    protected $model;

    /**
     * jwt的签发密钥，验证token的时候需要用到
     * @var
     */
    protected $key;

    /**
     * 获取路由地址
     * @param string $path
     * @param array $params
     * @param bool $suffix
     * @param bool $isDomain
     * @return \think\route\Url
     */
    public function url(string $path, array $params = [], bool $suffix = false, bool $isDomain = false)
    {
        return Url::buildUrl($path, $params)->suffix($suffix)->domain($isDomain)->build();
    }

    /**
     * 密码hash加密
     * @param string $password
     * @return false|string|null
     */
//    public function passwordHash(string $password)
//    {
//        return password_hash($password, PASSWORD_BCRYPT);
//    }

    /**
     * @param $name
     * @param $arguments
     * @return mixed
     */
    public function __call($name, $arguments)
    {
        // TODO: Implement __call() method.
        return call_user_func_array([$this->model, $name], $arguments);
    }

    protected static function moveUploadFile($tempPath,$fileType){
        try {
            $tempPathArray = explode('/', $tempPath);
            $targetFoloder = app()->getRootPath() . 'public/static/upload/' . $fileType . '/' . $tempPathArray[1];
            if (!is_dir($targetFoloder))
                mkdir($targetFoloder, 0777, true);
            $targetPath = $targetFoloder . '/' . $tempPathArray[2];
            rename(app()->getRootPath() . 'runtime/storage/' . $tempPath, $targetPath);
        }catch (\Exception $e) {
            api_return(50001,'文件传输失败');
        }
        return $fileType . '/' . $tempPathArray[1]. '/' . $tempPathArray[2];
    }

    protected static function getUploadField($temp,$type,$field)
    {
        if($field)
            @unlink(app()->getRootPath() . 'public/static/upload/'.$field);
        return self::moveUploadFile($temp, $type);
    }

    /**
     * 获取用户列表权限
     * @param $adminInfo
     * @param $field
     * @return array
     */
    public static function getAdminListPermission($adminInfo,$field){
        switch ($adminInfo->role){
            case 1:
                $op='<>';
                $condition='-1';
                break;
            default:
                $op='=';
                $condition=$adminInfo->id;
        }
        return [$field,$op,$condition];

    }

    /**
     * 验证表单提交数据
     * @param $rule 规则
     * @param $p 参数
     * @return void
     */
    protected static function validateRule($rule,$p=[]){
        $validate=Validate::rule($rule);
        if(!$validate->check($p))
            api_return(500,$validate->getError());
    }
}
